﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ThreadAndTaskInForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        int i = 0;
        private void Form1_Load(object sender, EventArgs e)
        {
            int threadId = Thread.CurrentThread.ManagedThreadId;
            Console.WriteLine("当前线程的ID是：" + threadId);

            // 1.执行本文档中的async方法。不需要Invoke
            AddNum();

            // 2.执行Task.Run方法。需要Invoke
            AddNumInTask();

            // 3.在其它类中执行线程方法
            Helper.AddNum(textBox1);
        }

        private async void AddNum()
        {
            await Task.Delay(3000);
            int threadId = Thread.CurrentThread.ManagedThreadId;
            Console.WriteLine("方法中的线程的ID是：" + threadId);
            while (true)
            {
                await Task.Delay(500);
                textBox1.Text = (i++).ToString();
            }
        }

        private void AddNumInTask()
        {
            Task.Run(async () =>
            {
                Console.WriteLine("方法2中的线程的ID是：" + Thread.CurrentThread.ManagedThreadId);
                while (true)
                {
                    await Task.Delay(500);
                    // 一定要用异步方法！！！！
                    Invoke(new Action(() =>
                    {
                        textBox1.Text = (i++).ToString();
                    }));
                }
            });
        }
    }
}
